package service.impl;

import dao.UserDao;
import dao.impl.UserDaoImpl;
import entity.PageResult;
import entity.User;
import service.UserService;

import java.util.List;

public class UserServiceImpl implements UserService {
    private UserDao userDao = new UserDaoImpl();

    @Override
    public PageResult<User> page(int pageNum, int size) {
        PageResult<User> page = new PageResult<>();

        //设置结果集
        int start = (pageNum-1)*size;
        List<User> users = userDao.findPage(start,size);
        page.setData(users);

        /**
         * 先计算总页码
         */
        long total = userDao.total();
        //总页码
        int totalPages = 0;
        //开始页码
        int begin = 0;
        //结束页码
        int end = 0;

        if (total % size == 0){
            //能整除
            totalPages = (int) (total/size);
        }else{
            totalPages = (int) (total/size) + 1;
        }

        System.out.println(totalPages);

        if (totalPages<=4){
            begin = 1;
            end = totalPages;
        }else {
            begin = pageNum - 2;
            //防止越界
            if (begin <= 0) {
                begin = 1;
            }

            end = pageNum + 1;
            //防止越界
            if (end >= totalPages){
                end = totalPages;
            //补齐4页
            }else if (end <= 4){
                end = 4;
            }

            //如果是最后一页，补齐4页
            if (end == totalPages){
                begin = end - 3;
            }
        }

        //设置begin页码
        page.setBegin(begin);

        //设置end页码
        page.setEnd(end);

        //设置当前页码
        page.setCurrent(pageNum);

        return page;
    }

    @Override
    public User findOne(int id) {
        return userDao.findById(id);
    }

    @Override
    public int update(User user) {
        return userDao.update(user);
    }
}
